//
//  RootViewController.m
//  iGameApp
//
//  Created by lanou on 16/1/9.
//  Copyright © 2016年 WYC. All rights reserved.
//

#import "RootViewController.h"
#import "IGRootTableViewCell.h"
#import "IGRightTabBarController.h"
#import "IGLoginViewController.h"
#import "IGRootAboutUsView.h"
#import "IGProvideAdviceView.h"
#import "IGHistoryListTableViewController.h"
#import "IGChangePasswordViewController.h"

@interface RootViewController () <UITableViewDataSource, UITableViewDelegate, UIAlertViewDelegate, UMSocialUIDelegate, UITextViewDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate>

@property (nonatomic, strong) IGRightTabBarController *rightTBC;

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong) NSMutableDictionary *dataDic;

@property (nonatomic, strong) NSMutableDictionary *imageDic;

@property (nonatomic, strong) NSArray *keysArr;

@property (nonatomic, strong) NSFileManager *manager;

@property (nonatomic, strong) UIView *backGroundView;
@property (nonatomic, strong) IGProvideAdviceView *provideAdviceView;
@property (weak, nonatomic) IBOutlet UIButton *userNameButton;
@property (weak, nonatomic) IBOutlet UIButton *userIconButton;

@property (nonatomic, strong) UIImagePickerController *imagePickerController;

@end

@implementation RootViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    [IG_UserMessage shareUserMessage].dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"userInfo"];
    [IG_UserMessage shareUserMessage].isLoading = [[NSUserDefaults standardUserDefaults] boolForKey:@"isLoading"];
    
    if ([IG_UserMessage shareUserMessage].isLoading == YES) {
        NSDictionary *dic  =[IG_UserMessage shareUserMessage].dic;
        [self.userNameButton setTitle:dic[@"nickname"] forState:(UIControlStateNormal)];
        [self.userIconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"user_img"]] forState:(UIControlStateNormal) placeholderImage:[UIImage imageNamed:@"uicon"]];
    }
    
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"USER" context:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self forKeyPath:@"LOGOUT" context:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 注册cell
    [_tableView registerNib:[UINib nibWithNibName:@"IGRootTableViewCell" bundle:nil] forCellReuseIdentifier:@"RootCell"];
    
    // 表头高度
    _tableView.rowHeight = _tableView.frame.size.height / 11;
    
    // 初始化字典
    _dataDic = [NSMutableDictionary dictionary];
    _dataDic[@"1"] = @[@"历史记录",@"修改密码"];
    _dataDic[@"2"] = @[@"清除缓存",@"分享iGame给好友",@"关于",@"意见反馈",@"登出"];
    
    _imageDic = [NSMutableDictionary dictionary];
    _imageDic[@"1"] = @[@"history",@"comment",@"password"];
    _imageDic[@"2"] = @[@"clean",@"share",@"about",@"question",@"exit"];
    
    
    // 初始化数组
    _keysArr = @[@"1",@"2"];
    
    // 添加rightTBC
    [self addRightTBC];
    
    // 刷新tableView的通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(refreshTableView) name:@"refresh" object:nil];
    [center addObserver:self selector:@selector(notice:) name:@"USER" object:nil];
}
- (void)refreshTableView
{
    [_tableView reloadData];
}

- (void)notice:(NSNotification *)sender {
    if ([IG_UserMessage shareUserMessage].isLoading == YES) {
        NSDictionary *dic  =[IG_UserMessage shareUserMessage].dic;
        [self.userNameButton setTitle:dic[@"nickname"] forState:(UIControlStateNormal)];
        [self.userIconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:dic[@"user_img"]] forState:(UIControlStateNormal) placeholderImage:nil];
    }
}
#pragma mark -- 添加rightTBC
- (void)addRightTBC
{
    _rightTBC = [[IGRightTabBarController alloc] init];
    CGRect frame = self.view.bounds;
    _rightTBC.view.frame = frame;
    [self.view addSubview:_rightTBC.view];
    
}

#pragma mark -- tableView dataSource

// 区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return _dataDic.allKeys.count;
}

// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSString *key = _keysArr[section];
    NSArray *valueArr = _dataDic[key];
    return valueArr.count;
}

// cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    IGRootTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RootCell"];
    
    NSString *key = _keysArr[indexPath.section];
    
    NSArray *valueArr = _dataDic[key];
    NSString *functionStr = valueArr[indexPath.row];
    if ([functionStr isEqualToString:@"清除缓存"]) {
        CGFloat cache = [self folderSizeAtPath];
        functionStr = [NSString stringWithFormat:@"清楚缓存 (%.1fM)",cache];
    }
    NSArray *imageArr = _imageDic[key];
    NSString *imageStr = imageArr[indexPath.row];

    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.functionLabel.text = functionStr;
    if ([functionStr isEqualToString:@"登出"]) {
        cell.functionLabel.textColor = [UIColor yellowColor];
    }
    cell.iconImageView.image = [UIImage imageNamed:imageStr];
    return cell;
}

// 表头
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return nil;
    }else{
    
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - 50, 5)];
    UILabel *lineLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 2.5, kScreenWidth - 50, 0.5)];
    lineLabel.backgroundColor = [UIColor grayColor];
    [headerView addSubview:lineLabel];
    
    return headerView;
    }
    
}

// 区头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 1) {
        return 0;
    }else{
        return 15;
    }
    
}

// cell点击
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            IGHistoryListTableViewController *listVC = [[IGHistoryListTableViewController alloc] init];
            [self.navigationController pushViewController:listVC animated:YES];
        }
        
        if (indexPath.row == 1) {
            
            [self changePassword];
            
        }
    }
    
    if (indexPath.section == 1){
        if (indexPath.row == 0) {
            [self clearCache];
        }else if (indexPath.row == 1){
            [self share];
        }else if (indexPath.row == 2){
            [self addAboutUsView];
        }else if (indexPath.row == 3){
            [self addProvideAdviceView];
        }else if (indexPath.row == 4){
            [self quitLogin];
        }
    }
}

// 第三方分享
- (void)share
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"569748dd67e58e9965001f37"
                                      shareText:@"欢迎使用iGame"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToWechatSession,UMShareToQQ,UMShareToEmail,UMShareToWechatFavorite,UMShareToQQ,UMShareToQzone,UMShareToSms, nil]
                                       delegate:self];
}

// 修改密码
- (void)changePassword
{
    IGChangePasswordViewController *changePasswordVC = [[IGChangePasswordViewController alloc] initWithNibName:@"IGChangePasswordViewController" bundle:nil];
    IGLoginViewController *loginVC = [[IGLoginViewController alloc] initWithNibName:@"IGLoginViewController" bundle:nil];
    
    if ([IG_UserMessage shareUserMessage].isLoading == YES) {
        
        [self.navigationController pushViewController:changePasswordVC animated:YES];
        
    }else{
        [self presentViewController:loginVC animated:YES completion:nil];
    }
    
    
    
}

// 清除缓存
- (void)clearCache
{
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"清除缓存" message:@"确认清除?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
    alertView.tag = 3000;
    [alertView show];
}

#pragma mark ---  UIAlertView 代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 3000) {
        if (buttonIndex == 1) {
            NSString *path =  [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
            path = [path stringByAppendingPathComponent:@"/default"];
            NSLog(@"%@",path);
            [_manager removeItemAtPath:path error:nil];
            [_tableView reloadData];
        }
    }
    
    if (alertView.tag == 4000) {
        if (buttonIndex == 0) {
            [_userNameButton setTitle:@"未登录" forState:(UIControlStateNormal)];
            [_userIconButton setBackgroundImage:[UIImage imageNamed:@"uicon"] forState:(UIControlStateNormal)];
        }
    }
}

// 返回文件大小
- (float ) folderSizeAtPath
{
    NSString *folderPath =  [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"/default"];
    _manager = [NSFileManager defaultManager];
    if (![_manager fileExistsAtPath:folderPath]) return 0;
    NSEnumerator *childFilesEnumerator = [[_manager subpathsAtPath:folderPath] objectEnumerator];
    NSString *fileName;
    long long folderSize = 0;
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        NSString *fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/(1024.0*1024.0);
}
// 计算文件夹大小
- (long long) fileSizeAtPath:(NSString *) filePath
{
    if ([_manager fileExistsAtPath:filePath]){
        return [[_manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

// 关于我们
- (void)addAboutUsView
{
    _backGroundView = [[UIView alloc] initWithFrame:self.view.frame];
    _backGroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:_backGroundView];
    
    IGRootAboutUsView *aboutUsView = [[UINib nibWithNibName:@"IGRootAboutUsView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    aboutUsView.frame = CGRectMake(30, kScreenHeight, kScreenWidth - 60, kScreenHeight - 100);
    [_backGroundView addSubview:aboutUsView];
    
    [aboutUsView.cancerButton addTarget:self action:@selector(removeView) forControlEvents:(UIControlEventTouchUpInside)];
    
    [UIView animateWithDuration:.3 animations:^{
        aboutUsView.frame = CGRectMake(30, 50, kScreenWidth - 60,kScreenHeight - 100);
    }];
}

// 意见反馈
- (void)addProvideAdviceView
{
    _backGroundView = [[UIView alloc] initWithFrame:self.view.frame];
    _backGroundView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
    [self.view addSubview:_backGroundView];
    
    _provideAdviceView = [[UINib nibWithNibName:@"IGProvideAdviceView" bundle:nil] instantiateWithOwner:self options:nil].firstObject;
    _provideAdviceView.frame = CGRectMake(30, kScreenHeight, kScreenWidth - 60, kScreenHeight - 100);
    [_backGroundView addSubview:_provideAdviceView];
    
    [_provideAdviceView.cancerButton addTarget:self action:@selector(removeView) forControlEvents:(UIControlEventTouchUpInside)];
    
    [UIView animateWithDuration:.3 animations:^{
        _provideAdviceView.frame = CGRectMake(30, 50, kScreenWidth - 60,kScreenHeight - 100);
    }];
    
    UIView *inputAccessoryView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
    inputAccessoryView.backgroundColor = [UIColor whiteColor];
    UIButton *finishButton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    finishButton.frame = CGRectMake(kScreenWidth - 60, 10, 50, 20);
    [finishButton setTitle:@"完成" forState:(UIControlStateNormal)];
    [finishButton setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];
    [finishButton addTarget:self action:@selector(finishButtonEndEdit) forControlEvents:(UIControlEventTouchUpInside)];
    [inputAccessoryView addSubview:finishButton];
    _provideAdviceView.adviceTextView.inputAccessoryView = inputAccessoryView;
    _provideAdviceView.adviceTextView.delegate = self;
    [_provideAdviceView.sendButton addTarget:self action:@selector(sendButtonAction:) forControlEvents:(UIControlEventTouchUpInside)];
}

- (void)removeView
{
    [_backGroundView removeFromSuperview];
}

- (void)finishButtonEndEdit
{
    [self beginEditingAdviceAnimation];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self beginEditingAdviceAnimation];
}

- (void)beginEditingAdviceAnimation
{
    [UIView animateWithDuration:.3 animations:^{
        self.view.frame = CGRectMake(0, 0, kScreenWidth,kScreenHeight);
    }];
    [_provideAdviceView.adviceTextView endEditing:YES];
}

#pragma mark  --  UITextView代理方法
-(void)textViewDidBeginEditing:(UITextView *)textView
{
    [UIView animateWithDuration:.3 animations:^{
        self.view.frame = CGRectMake(0, -120, kScreenWidth,kScreenHeight);
    }];
}

- (void)sendButtonAction:(UIButton *)sender
{
#warning 发送意见反馈
    NSLog(@"%@",_provideAdviceView.adviceTextView.text);
}

- (IBAction)pushToLogin:(UIButton *)sender {
    
    IG_UserMessage *user = [IG_UserMessage shareUserMessage];
    BOOL isLogin = user.isLoading;
    
    if (isLogin == NO) {
        // 未登录
        IGLoginViewController *loginVC = [[IGLoginViewController alloc] init];
        [self presentViewController:loginVC animated:YES completion:nil];
//        __weak RootViewController *mySelf = self;
//        loginVC.loginSuccessBlock = ^void(NSDictionary *dataDic){
//            [mySelf.userNameButton setTitle:dataDic[@"nickname"] forState:(UIControlStateNormal)];
//            [mySelf.userIconButton sd_setBackgroundImageWithURL:[NSURL URLWithString:dataDic[@"user_img"]] forState:(UIControlStateNormal) placeholderImage:nil];
//        };
//    }else{
//        // 已经登录
//        NSLog(@"已经登录");
//    }
    
    }else{
    
//        [self pushToPhoto];
    
    }
    
}

// 相册
- (void)pushToPhoto
{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction *takePhoto = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        _imagePickerController = [[UIImagePickerController alloc] init];
        
        // 支持照相功能
        _imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
        // 相机支持的类型
        _imagePickerController.mediaTypes = @[(NSString *)kUTTypeImage];
        // 相机捕捉的类型
        _imagePickerController.cameraCaptureMode = UIImagePickerControllerCameraCaptureModePhoto;
        // 代理
        _imagePickerController.delegate = self;
        // 是否允许编辑
        _imagePickerController.allowsEditing = YES;
        
       
        
        [self presentViewController:_imagePickerController animated:YES completion:nil];
        
    }];
    
    [alertController addAction:takePhoto];
    
    UIAlertAction *pictures = [UIAlertAction actionWithTitle:@"从照片获取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        
        imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        [self presentViewController:imagePickerController animated:YES completion:nil];
        
    }];
    
    [alertController addAction:pictures];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        ;
    }];
    
    [alertController addAction:cancel];
    
    [self presentViewController:alertController animated:YES completion:nil];
    
    
}

- (void)cancelCamera{
    [_imagePickerController dismissViewControllerAnimated:YES completion:nil];
}

-(void)savePhoto{
    //拍照，会自动回调- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info，对于自定义照相机界面，拍照后回调可以不退出实现连续拍照效果
//    [_imagePickerController takePicture];
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
   /*
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    25         // 设置时间格式
    26         formatter.dateFormat = @"yyyyMMddHHmmss";
    27         NSString *str = [formatter stringFromDate:[NSDate date]];
    28         NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
    
    */
    
    NSData *currentData = [NSData data];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *fileName = [formatter stringFromDate:currentData];
    
    
    [self saveImage:image withName:[NSString stringWithFormat:@"%@.jpg",fileName]];
    
    NSString *fullPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.jpg",fileName]];
    UIImage *saveImage = [[UIImage alloc] initWithContentsOfFile:fullPath];
    
    
    // 保存到相册中, 需要使用函数
    UIImageWriteToSavedPhotosAlbum(saveImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);

    
 //   [self upDateImage:image withfileName:fileName];
    
    
}

#pragma mark--------------保存图片--------------
- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName{
    // 1为不缩放保存, [0.0---1.0];
    // 相机 照出图片格式为jpg
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 1);
    // 获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    [imageData writeToFile:fullPath atomically:NO];
    
}

// 通过回调方法,可以知道 保存是否成功
-(void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    
}


- (void)upDateImage:(UIImage *)image withfileName:(NSString *)fileName
{

    NSMutableDictionary *parDic = [NSMutableDictionary dictionary];
    NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"http://www.imbatv.cn/api_2_4_0/upload_Avatar" parameters:parDic constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        [formData appendPartWithFileURL:[NSURL fileURLWithPath:@"file://path/to/image.jpg"] name:@"file" fileName:[NSString stringWithFormat:@"%@.jpg",fileName] mimeType:@"image/jpeg" error:nil];
    } error:nil];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
    
    NSURLSessionUploadTask *uploadTask;
    uploadTask = [manager
                  uploadTaskWithStreamedRequest:request
                  progress:^(NSProgress * _Nonnull uploadProgress) {
                      // This is not called back on the main queue.
                      // You are responsible for dispatching to the main queue for UI updates
                      dispatch_async(dispatch_get_main_queue(), ^{
                          //Update the progress view
                     //     [progressView setProgress:uploadProgress.fractionCompleted];
                      });
                  }
                  completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                      if (error) {
                          NSLog(@"Error: %@", error);
                      } else {
                          NSLog(@"%@ %@", response, responseObject);
                      }
                  }];
    
    [uploadTask resume];

    
}


#pragma mark---------------点击cancel点用的方法---------
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker{
    NSLog(@"cancel");
    [self dismissViewControllerAnimated:YES completion:nil];
}



// 登出
- (void)quitLogin
{
    if ([[_userNameButton titleForState:(UIControlStateNormal)] isEqualToString:@"未登录"]) {
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"您还未登录" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles: nil];
        [alertView show];
    }else{
        
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"登出" message:@"确认登出?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            [IG_UserMessage shareUserMessage].isLoading = NO;
            [IG_UserMessage shareUserMessage].dic = nil;
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"userInfo"];
            [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"isLoading"];
            
            [[NSNotificationCenter defaultCenter] postNotificationName:@"LOGOUT" object:nil userInfo:nil];
            [_userIconButton setBackgroundImage:[UIImage imageNamed:@"uicon"] forState:UIControlStateNormal];
            
        }];
        [alertController addAction:action];
        
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
        [alertController addAction:action1];
        
        [self presentViewController:alertController animated:YES completion:nil];
        
        
    }
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
